package controllers;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.AutoSite;
import models.Blog;

import data.AutoSiteData;
import data.BlogData;

public class DeleteBlogServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		//Get blogID
		String path = ((HttpServletRequest) request).getRequestURI();
		String blogId = URLDecoder.decode(path.toLowerCase().replaceAll("/delete-blog/", ""),"UTF-8");
		
		//Delete site in this blog
		AutoSiteData aData = new AutoSiteData();
		ArrayList<AutoSite> sites = aData.getByBlogId(blogId);
		for (int i = 0; i < sites.size(); i++) {
		    aData.delete(sites.get(i));
		}
		
		//Delete blog
		BlogData blogData = new BlogData();
		Blog blog = blogData.getById(blogId);
		if (blog == null) {
			response.sendRedirect("/message?txt=page-not-found");
			return;
		}
		blogData.delete(blog);
		
		response.sendRedirect("/view-profile");
	}
}
